﻿using Newtonsoft.Json;
using RestSharp;
using SIMS.Common.Models;
using SIMS.Shared.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SIMS.Common.RestClient
{
    public class HttpRestClient
    {
        private readonly RestSharp.RestClient _client;

        private readonly string baseUrl = "http://localhost:5000/";

        public HttpRestClient()
        {
            _client = new RestSharp.RestClient(baseUrl);
        }

        public async Task<ResponseResultModel> Execute(ApiRequest apiRequest)
        {
            RestRequest request = new RestRequest(apiRequest.Route, apiRequest.Method);
            request.AddHeader("Content-Type", apiRequest.ContentType);

            if (apiRequest.Method == Method.Put || apiRequest.Method == Method.Post)
            {                                                                                                    
                if (apiRequest.Parameters != null)
                {
                    request.AddBody(apiRequest.Parameters);
                }
            }
            else 
            {
                if (apiRequest.Parameters is Dictionary<string, object>) 
                {
                    var p = apiRequest.Parameters as Dictionary<string, object>;
                    foreach(var m in p)
                    {
                        if (m.Value != null) 
                        {
                            request.AddQueryParameter(m.Key, m.Value.ToString());
                        }
                        else
                        {
                            request.AddQueryParameter(m.Key, "");
                        }
                    }
                }
            }
            
            var response = await _client.ExecuteAsync(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return JsonConvert.DeserializeObject<ResponseResultModel>(response.Content);
            }
            else
            {
                return new ResponseResultModel { code =(int)response.StatusCode, msg = response.ErrorMessage, data = null };
            }
        }
    }
}
